angular.module('magazinectroller',[])
.controller('CatalogCtrl',function($scope,$state,$stateParams,Loading,Magazine,History){
      var magazineId = $stateParams['magazineId'];
    $scope.goback = function(){
      History.goback();
    }

    $scope.doRefresh = function(){
      Magazine.getChapterListInfo(magazineId);
    }
    //获取章节信息
    Loading.showLoading();
    Magazine.getChapterListInfo(magazineId);
      $scope.$on('Magazine.chapterListUpdated',function(){
        Loading.hideLoading();
        $scope.$broadcast('scroll.refreshComplete');
        var result= Magazine.getChapterListJson();
        $scope.bookName = result.bookTitle;
        $scope.chapterList=result.chapterList;
      });
  })
  .controller('CatalogDetailCtrl',function($scope,$rootScope,$state,$stateParams,$cordovaStatusbar,$ionicActionSheet,$cordovaFileTransfer,$timeout,Loading,Magazine,MagazineComment,Storage,History,Toast){
    //获取到章节详情的编号
    var bdId = $stateParams['bdId'];
    //会员编号
    var memberId = '';
    var items = [];
    var pswpElement = document.querySelectorAll('.pswp')[0];
    //点击查看大图，并获取图片保存图片
    $scope.$on('$ionicView.afterEnter',function(){
      $timeout(function(){
        var imgObjList = document.getElementById('bookDetail').getElementsByTagName('img');
        for(i=0;i<imgObjList.length;i++){
          var temp = {
            src:imgObjList[i].src,
            w:imgObjList[i].naturalWidth,
            h:imgObjList[i].naturalHeight
          };
          items.push(temp);
          imgObjList[i].onclick = function(){
            var options = {
              index: i,
              history: false,
              focus: false,
              loop: false,
             /* pinchToClose:false,
              closeOnVerticalDrag:false,*/
              showAnimationDuration: 100,
              hideAnimationDuration: 100,
              backButtonHideEnabled:true,
              captionAndToolbarFlipPosition:true,
              loadingIndicatorDelay:100
            };
            $rootScope.gallery  = new PhotoSwipe(pswpElement,PhotoSwipeUI_Default,items,options);
            $rootScope.gallery.init();
           // $cordovaStatusbar.hide();
          }
        }
      },2000);
      //长按下载
      $rootScope.downloadHomeImg = function(){
        var url = $rootScope.gallery.currItem.src;
        var timestamp=new Date().getTime();
        var targetPath = cordova.file.externalRootDirectory+"winelife/winelife_book_"+timestamp+".jpg";
        var trustHosts = true;
        var options = {};
        $ionicActionSheet.show({
          buttons: [
            {text: '保存到手机相册'}
          ],
          cancelText: '取消',
          buttonClicked: function (index) {
            if(index==0){
              $cordovaFileTransfer.download(url, targetPath, options, trustHosts)
                .then(function(result) {
                  Toast.showMessage("保存成功");
                }, function(err) {
                  Toast.showMessage("保存成功");
                }, function (progress) {
                });
            }
            return true;
          }
        });
      }
      $rootScope.smallPicture = function(){
        $rootScope.gallery.close();
       // $cordovaStatusbar.show();
      }
    });
    //返回
    $scope.goback = function(){
      History.goback();
    }
    //进入页面时
    var firstInbookDetail = true;
    $scope.$on('$ionicView.beforeEnter',function(){
      memberId = Storage.get("member").member_id;
      if(firstInbookDetail){
        Loading.showLoading();
        firstInbookDetail = false;
      }
      Magazine.getContent(bdId,memberId);  //获取正文
    });
    //当service访问网络成功时，调用该方法
    $scope.$on('Magazine.CommentCountUpdated', function(){
       var result =MagazineComment.getCommetCountJson();
      $scope.bookContent.bd_comment_num = result.bd_comment_num;
      $scope.bookContent.lcdStatus = result.lcdStatus;
      $scope.bookContent.mcdStatus = result.mcdStatus;
    });
    //给章节详情点赞
    var likeBding = false;
     $scope.likeBd = function(){
       if(!likeBding){
         Loading.showLoading();
         Magazine.likeBd(bdId,memberId);
         likeBding = true;
       }
    }
    $scope.$on('Magazine.likeBdUpdated',function(){
      Loading.hideLoading();
      likeBding = false;
      var result = Magazine.getLikeJson();
      Toast.showMessage(result.lcdMsg);
      $scope.bookContent.lcdStatus = result.lcdStatus;
    })
    //收藏章节详情
    var collectBding = false;
     $scope.collectBd= function(){
       if(!collectBding){
         Loading.showLoading();
         Magazine.collectBd(bdId,memberId);
         collectBding = true;
       }
    }
    $scope.$on('Magazine.collectBdUpdated',function(){
      Loading.hideLoading();
      collectBding = false;
      var result = Magazine.getCollectJson();
      $scope.bookContent.mcdStatus = result.mcdStatus;
      Toast.showMessage(result.mcdMsg);
    })

    $scope.$on('Magazine.BookDetailUpdated',function(){
      Loading.hideLoading();
      $scope.$broadcast('scroll.refreshComplete');
      $scope.bookContent = Magazine.getContentJson();
      //Storage.set("bdTitle",$scope.bookContent.bd_chapter_info);//保存在本地
    })
  })

  //杂志详情和丛书详情的评论
  .controller("MagazineCommentCtrl",function($scope,$stateParams,$ionicPopup,Loading,Toast,MagazineComment,ENV,Storage,History){

    var bdId=$stateParams['bdId'];
    var memberId = '';
    var isFirstIn = true;
    $scope.picPath = ENV.picPath;
    $scope.$on('$ionicView.beforeEnter',function(){
      memberId = Storage.get('member').member_id;
      if(isFirstIn){
        Loading.showLoading();
        isFirstIn = false;
      }
      //获取评论列表
      MagazineComment.getCommentList(bdId,memberId);
    });
    //删除评论
    var deleteIndex = '';
    $scope.deleteComment = function(commentId,index){
      $ionicPopup.confirm({
        template: '<p style="text-align: center;font-size:16px;">确定要删除该评论吗？</p>',
        cancelText: '取消',
        okText: '确定',
        okType: 'hd-red-btn',
        cancelType: 'cancel-esc-btn'
      }).then(function (res) {
        if (res) {
          Loading.showLoading();
          MagazineComment.deleteComment(commentId,memberId,bdId);
          deleteIndex = index;
        }
      });
    }
    $scope.$on('MagazineComment.deleteCommentUpdated',function(){
      Loading.hideLoading();
      var result = MagazineComment.getDelCommentJson();
      if(result.dmCommentStatus){
        $scope.bdCommentList.splice(deleteIndex,1);
      }
      Toast.showMessage(result.dmCommentMsg);
    });
    //返回
    $scope.goback = function(){
      History.goback();
    }
    //新增评论
    $scope.comment={
      newComment:''
    };
   /* $scope.$on('$ionicView.loaded', function () {
      Loading.showLoading();
      MagazineComment.getCommentList(bdId,memberId);
    });*/
    //请求网络数据完成之后
    $scope.$on('Magazine.CommentUpdated', function() {
      Loading.hideLoading();
      $scope.bdCommentList = MagazineComment.getCommentJson();
      $scope.memberInfo = MagazineComment.getMemberInfo();
      $scope.bdTitle = MagazineComment.getBdTitleJson();//获取到章节详情的标题
      $scope.$broadcast('scroll.refreshComplete');
    });
    //加载更多
    $scope.loadMore = function(){
      MagazineComment.getMoreCommentList(bdId,memberId);
    }
    //是否有下一页
    $scope.hasNextPage = function(){
      return MagazineComment.hasNextPage();
    }
    //下拉刷新
    $scope.doRefresh = function(){
      MagazineComment.getCommentList(bdId,memberId);
    }
    $scope.$on('Magazine.MoreCommentListUpdated', function() {
      $scope.bdCommentList = MagazineComment.getCommentJson();
      $scope.$broadcast('scroll.infiniteScrollComplete');
    });
    //发表评论
    $scope.publishComment = function(){
      if($scope.comment.newComment==''){
        Toast.showMessage("评论的内容不能为空");
      }else{
        Loading.showLoading();
        MagazineComment.publishComment(bdId,memberId,$scope.comment.newComment);
        $scope.comment.newComment = '';//使得输入框中的值为空
      }
    };
    //请求网络数据完成之后
    $scope.$on('Magazine.publishCommentUpdated', function() {
      Loading.hideLoading();
      var newComment = MagazineComment.getNewComment();
      if(newComment.mcommentStatus){
        $scope.bdCommentList.unshift(newComment);
      }
      Toast.showMessage(newComment.mcommentMsg);
    });
  }).filter(
  'to_trusted', ['$sce', function ($sce) {
    return function (text) {
      return $sce.trustAsHtml(text);
    }
  }])
;

